package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;


    @Transactional     //添加事务
    @Override
    public void saveWithFlavor(DishDTO dishDTO) {

        /**
         * 1. 保存菜品数据到菜品表dish
         * 2. 将dishDTO拷贝到dish对象中
         * 3.将dish插入到表中（注意：需要插入后的返回值）
         * 4.从dishDTO中获取dishFlavors集合
         * 5.遍历dishFlavors集合，设置dish的id
         * 6.批量保存dishFlavors到dish_flavor表
         *
         */

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.insert(dish);

        dishDTO.getFlavors().forEach(flavor -> {
            flavor.setDishId(dish.getId());
        });
        if (dishDTO.getFlavors() != null && dishDTO.getFlavors().size() > 0){
            dishFlavorMapper.insertBatch(dishDTO.getFlavors());
        }

    }

    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        //使用PageHelper插件自动进行分页查询
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page page = dishMapper.page(dishPageQueryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void delete(Long[] ids) {
        /**
         * 1.遍历数组获取id
         * 2.如果当前菜品再启售中，不能删除
         * 3.如果当前菜品有套餐关联，不能删除
         * 4.如果当前菜品有口味，需要一并删除
         */
        for (Long id : ids) {
            Dish dish = dishMapper.findById(id);
            if (dish.getStatus() == StatusConstant.ENABLE){
                //当前菜品在启售中，不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }

            List<SetmealDish> setmealDishes = setmealDishMapper.getByDishId(id);
            if (setmealDishes != null && setmealDishes.size() > 0){
                //当前菜品有套餐关联，不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }
            //删除菜品数据
            dishMapper.delete(id);
            //删除口味数据
            dishFlavorMapper.deleteByDishID(id);
        }
    }

    @Override
    public DishVO getByIdWithFlavor(Long id) {
        /**
         * 1.去Dish表中查询菜品数据
         * 2.去DishFlavor表中查询口味数据
         * 3.将Dish和DishFlavor数据封装到DishVO中并返回
         */
        Dish dish = dishMapper.findById(id);
        List<DishFlavor> dishFlavors = dishFlavorMapper.findByDishId(id);
        DishVO dishVO = new DishVO();
        //拷贝属性
        BeanUtils.copyProperties(dish,dishVO);
        //封装口味数据
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    @Transactional
    @Override
    public void updateWithFlavors(DishDTO dishDTO) {
        /**
         * 1.修改dish表（DishDTO--》Dish）
         * 2.删除dish_flavor表的数据
         * 3.批量插入dish_flavor表
         */

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.update(dish);
        dishFlavorMapper.deleteByDishID(dishDTO.getId());
        //批量插入
        List<DishFlavor> flavors = dishDTO.getFlavors();

        flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishDTO.getId()));
        if (flavors != null && flavors.size()>0){
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    @Override
    public void startOrStop(Integer status, Long id) {
        //设置当前菜品状态
        Dish dish = new Dish();
        dish.setId(id);
        dish.setStatus(status);
        dishMapper.update(dish);
    }

    @Override
    public List<Dish> list(Long categoryId) {
        List<Dish> list = dishMapper.list(categoryId);
        if (list != null && list.size() > 0){
            return list;
        }
        return List.of();
    }
}
